from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# 定义JSON格式要求
prompt = ChatPromptTemplate.from_template("""
回答以下问题，返回JSON格式:
{{
    "answer": "答案文本",
    "confidence": 置信度 (0-1)
}}
问题: {question}
""")

# 创建模型
model = ChatOpenAI(
    model_name = "qwen-plus",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    api_key="sk-005c3c25f6d042848b29d75f2f020f08",
    temperature=0.7
)

parser = JsonOutputParser()
chain = prompt | model | parser

#调用
result = chain.invoke({"question": "地球半径是多少"})
print(result)